/************************************
 * INIT
 ************************************/
 
var jsonLinks = [];
var toggleSortedByDate = true; // sorted by date from the start
var toggleSortedByUrl = false;
var toggleSortedByColor = false;
 
var delPrefix = "del"; // used to build element ids like "del0,del1,.."
var markedUrlsForRemoval = [];

function init() {
    _e("btnApply").value = chrome.i18n.getMessage("manager_apply");
    _e("btnCancel").value = chrome.i18n.getMessage("manager_cancel");
    _e("sortby").innerText = chrome.i18n.getMessage("manager_sort")+" : ";
    
    // extracting keys and values from localStorage
    fillJsonLinks();
    
    // by date is the probably the most popular request..
    sortByDate();
    
    // display table
    disp();
}

/************************************
 * EVENTS
 ************************************/
function btnApply_Click() {
    removeMarked();
    window.close();
}

function btnCancel_Click() {
    window.close();
}

/************************************
 * METHODS
 ************************************/
// fill urls, colors and dates with data from localStorage
function fillJsonLinks() {
    for (var i=0,len=localStorage.length; i<len; i++){
        var url = window.localStorage.key(i);
        var obj = JSON.parse(getKey(url));
        jsonLinks[i] = {
            "url": url,
            "color": obj.color,
            "date": obj.date,
            "remove": false
        };
    }
}

function sortByDate() {
    toggleSortedByDate = !toggleSortedByDate;
    jsonLinks = jsonLinks.sort(byDate);
    disp();
}

function byDate(a,b) {
    return toggleSortedByDate ? a.date > b.date : a.date < b.date;
}

function sortByUrl() {
    toggleSortedByUrl = !toggleSortedByUrl;
    jsonLinks = jsonLinks.sort(byUrl);
    disp();
}
function byUrl(a,b) {
    return toggleSortedByUrl ? a.url < b.url : a.url > b.url;
}

function sortByColor() {
    toggleSortedByColor = !toggleSortedByColor;
    jsonLinks = jsonLinks.sort(byColor);
    disp();
}
function byColor(a,b) {
    return toggleSortedByColor ? a.color < b.color : a.color > b.color;
}

function disp() {
    var content = ["<table>"];
    if (jsonLinks.length > 0) {
        // check if links is already marked for removal..
        for (var i=0; i<jsonLinks.length; i++) {
            var delLinkArgs = {
                "className": "del",
                "label": chrome.i18n.getMessage("manager_del_char"),
                "title": chrome.i18n.getMessage("manager_del_title"),
                "methodCall": ["markForRemoval(",i,")"].join("")
            };
            var j=0;
            var b=false;
            while (j<markedUrlsForRemoval.length && !b) {
                if (jsonLinks[i].url == markedUrlsForRemoval[j]) {
                    delLinkArgs.className = "undo";
                    delLinkArgs.label = chrome.i18n.getMessage("manager_undo_char"),
                    delLinkArgs.title = chrome.i18n.getMessage("manager_undo_title"),
                    delLinkArgs.methodCall = ["unmarkForRemoval(",i,")"].join("");
                }
                j++;
            }
            // create a new row
            var append = [
                "<tr>",
                "   <td><a class='",delLinkArgs.className,"' id='",delPrefix,i,"' title='",delLinkArgs.title,"' onclick='",delLinkArgs.methodCall,"'>",delLinkArgs.label,"</a></td>",
                "   <td><div class='square' style='background-color:",jsonLinks[i].color,";' title='",jsonLinks[i].color,"'></div></td>",
                "   <td><a class='url' href='#' onclick='redirectCurrentPageToUrl(\"",jsonLinks[i].url,"\")'>",jsonLinks[i].url,"</a></td>",
                "</tr>"
            ].join("");
            content.push(append);
        }
        content.push("</table>");
        _e("tags").innerHTML = content.join("");
    } else {
        _e("tags").innerHTML = chrome.i18n.getMessage("manager_nothing");
    }
}
 
function removeMarked() {
    for (var i=0; i<markedUrlsForRemoval.length; i++) {
        removeKey(markedUrlsForRemoval[i]);
    }
    /// update tags on current page
    /// Sends [cmd] to content script
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {
            cmd: "updateTags"
        });
    });
}
 
function markForRemoval(index) {
    markedUrlsForRemoval.push(jsonLinks[index].url);
    var sender = _e(delPrefix+index);
    sender.className = "undo";
    sender.innerHTML = chrome.i18n.getMessage("manager_undo_char");
    sender.title = chrome.i18n.getMessage("manager_undo_title");
    sender.onclick = function() {
        unmarkForRemoval(index);
    };
    
    if (_e("btnApply").disabled != "") {
        _e("btnApply").disabled = "";
    }
}

function unmarkForRemoval(index) {
    var i=0;
    var b = false;
    while (i<markedUrlsForRemoval.length && !b) {
        if (markedUrlsForRemoval[i] == jsonLinks[index].url) {
            delete markedUrlsForRemoval[i];
            b = true;
        }
        i++;
    }
    
    var sender = _e(delPrefix+index);
    sender.className = "del";
    sender.innerHTML = chrome.i18n.getMessage("manager_del_char");
    sender.title = chrome.i18n.getMessage("manager_del_title");
    sender.onclick = function() {
        markForRemoval(index);
    };
}

/************************************
 * UTILS
 ************************************/
 
function redirectCurrentPageToUrl(url) {
    // Sends [cmd, redirectUrl] to content script
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, {
            cmd: "redirectToUrl",
            redirectUrl: url
        });
    });
}

function getKey(key) {
    return window.localStorage.getItem(key);
}

function removeKey(key) {
    try {
        window.localStorage.removeItem(key);
    } catch (e) {
        console.log(DBG_APP_NAME+e);
    }
}
 
function _e(id) {
    return document.getElementById(id);
}
